package com.xyhuo.leetcode;

public class XmlValidationTest {

    // 标识当前解析位于XML注释内
    private boolean inComment;

    private static final String START_COMMENT = "<!--";
    private static final String END_COMMENT = "-->";

    private static final String DOCTYPE = "DOCTYPE";

    private String consumeCommentTokens(String line) {
        int indexOfStartComment = line.indexOf(START_COMMENT);
        if (indexOfStartComment == -1 && !line.contains(END_COMMENT)) {
            return line;
        }
        String result = "";
        String currLine = line;
        if (!this.inComment && (indexOfStartComment >= 0)) {
            result = line.substring(0, indexOfStartComment);
            currLine = line.substring(indexOfStartComment);
        }
        if ((currLine = consume(currLine)) != null) {
            result += consumeCommentTokens(currLine);
        }
        return result;
    }

    private String consume(String line) {
        int index = this.inComment ? endComment(line) : startComment(line);
        return (index == -1 ? null : line.substring(index));
    }

    /**
     * 判断line中是否有“注释开始符（START_COMMENT）”，
     * 如果有标记处于注释范围内，然后获取注释开始符的下一个字符的index；
     * 如果没有，返回-1
     *
     * @param line
     * @return
     */
    private int startComment(String line) {
        return commentToken(line, START_COMMENT, true);
    }

    /**
     * 判断line中是否有“注释结束符（END_COMMENT）”，
     * 如果有，标记不再处于注释范围内，然后获取注释结束符的下一个字符的index；
     * 如果没有，返回-1
     *
     * @param line
     * @return
     */
    private int endComment(String line) {
        return commentToken(line, END_COMMENT, false);
    }

    private int commentToken(String line, String token, boolean inCommentIfPresent) {
        int index = line.indexOf(token);
        if (index > -1) {
            this.inComment = inCommentIfPresent;
        }
        return (index == -1 ? index : index + token.length());
    }

    private boolean hasDocType(String content) {
        return content.contains(DOCTYPE);
    }

    private boolean hasOpeningTag(String content) {
        if (this.inComment) {
            return false;
        }
        int openTagIndex = content.indexOf('<');
        return (openTagIndex > -1 && (content.length() > openTagIndex + 1) && Character.isLetter(content.charAt(openTagIndex + 1)));
    }

    public static void main(String[] args) {
        XmlValidationTest test = new XmlValidationTest();
        String str = "<!--    gagaga <!--    hahahah -->  -->";
        String s = test.consumeCommentTokens(str);
        System.out.println(s);
    }
}
